package com.xunyin.schedule;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xunyin.enums.AppIdKeyEnum;
import com.xunyin.modules.commontokentemp.domain.TCommonTokenTemp;
import com.xunyin.modules.commontokentemp.service.TCommonTokenTempService;
import com.xunyin.utils.HttpClientUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
@EnableScheduling
public class MiniProgramAccessTokenSchedule {
    private Logger logger = LoggerFactory.getLogger(MiniProgramAccessTokenSchedule.class);

    private String GET_ACCESSTOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";

    @Autowired
    TCommonTokenTempService tCommonTokenTempService;

    //@Scheduled(fixedRate = 3600000)
    //@Scheduled(fixedRate = 10000)
    public void getAccessTokenTask() {
        for (AppIdKeyEnum appIdKeyEnum : AppIdKeyEnum.values()) {
            updateByAppId(appIdKeyEnum.getAppId(), appIdKeyEnum.getAppKey());
        }
    }

    private void updateByAppId(String appId, String appKey) {
        try {
            logger.info("========getAccessTokenTask=========appId = {}", appId);
            String url = GET_ACCESSTOKEN_URL.replace("APPID", appId);
            url = url.replace("APPSECRET", appKey);

            String result = HttpClientUtil.doGet(url);
            logger.info("MiniProgramAccessTokenSchedule get accesstoken result = {}", result);

            JSONObject jsonObject = JSON.parseObject(result);

            TCommonTokenTemp commonTokenTemp = new TCommonTokenTemp();
            commonTokenTemp.setTokenCode(jsonObject.getString("access_token"));
            commonTokenTemp.setUpdateTime(new Date());
            commonTokenTemp.setOfficialName(appId);
            commonTokenTemp.setUpdateTime(new Date());

            TCommonTokenTemp qryCommonTokenTemp = tCommonTokenTempService.selectByOfficialName(appId);
            if (qryCommonTokenTemp == null) {
                commonTokenTemp.setCreateTime(new Date());
                tCommonTokenTempService.save(commonTokenTemp);
            } else {
                tCommonTokenTempService.updateOfficialName(commonTokenTemp);
            }
        } catch (Exception e) {
            logger.error("MiniProgramAccessTokenSchedule fail -> {}", e);
        }

    }
}
